/* eslint-disable */
import axios from 'axios'
import router from '../router/index'

axios.defaults.timeout = 5000  //超时时间设置
axios.defaults.withCredentials = true  //true允许跨域
axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.baseURL = 'http://localhost:8888/api'

// 响应拦截器
axios.interceptors.response.use(
  response => {
    switch (response.status) {
      case 200:
        return Promise.resolve(response.data) //返回data{state,msg,data}
      case 401: {
        localStorage.removeItem('USER_INFO')
        window.location.href = '/login'
        return Promise.resolve(response)
      }
      default:
        return Promise.reject(response)
    }
  },
  error => {
    localStorage.removeItem('USER_INFO')
    return Promise.reject(error)
  })


// 全局拦截器,在进入需要用户权限的页面前校验是否已经登录
router.beforeResolve((to, from, next) => {
  console.log('beforeResolve--------')
  const user = localStorage.getItem('USER_INFO')
  console.log('user: '+ user)
  console.log('requireAuth: '+ to.meta.requireAuth)
  // 判断路由是否设置相应校验用户权限
  if (to.meta.requireAuth) {
    console.log('a')
    if (!user) {
      console.log('b')
      window.location.href = '/login'
      if (from.name === null) {
        console.log('c')
        next('/')
        return
      }
      console.log('d')
      next(false)
      return
    }
  }
  next()
})

export function get(url, params) {
  console.log("get:")
  console.log("url:" + url)
  console.log("params:" + params)
  return new Promise((resolve, reject) => {
    axios.get(url, {params: params}).then(response => {
      resolve(response);
    }).catch(err => {
      reject(err)
    })
  })
}

export function post(url, data) {
  console.log("post:")
  console.log("url:" + url)
  console.log("data:" + JSON.stringify(data))
  return new Promise((resolve, reject) => {
    axios.post(url, data).then(response => {
      resolve(response);
    }, err => {
      reject(err)
    })
  })
}
